<!--  -->
<template>
  <div style="">
    <el-card style="margin: 20px">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="菜单名称">
          <el-input v-model="queryStr" placeholder="请输入查询关键字" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="getMenuList">查询</el-button>
          <el-button v-has-permi="['/menu/saveMenu']" type="primary" icon="el-icon-check" @click="showAddMenuForm">新增菜单</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin: 0px 20px">
      <el-table :data="menuList" style="width: 100%" :row-class-name="tableRowClassName">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-table v-if="scope.row.children.length>0" :show-header="false" :data="scope.row.children" :row-class-name="tableRowClassName">
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-row v-for="(menu1,index1) in scope.row.children" :key="index1" class="vcenter">
                    <el-col style="width: 1000px">{{ menu1.name }}</el-col>
                    <el-col style="width: 1500px">{{ menu1.url }}</el-col>
                    <el-col style="width: 300px"><i :class="menu1.iconCls" /></el-col>
                    <el-col style="width: 400px">
                      <i v-if="menu1.menuLevel===1">菜单</i>
                      <i v-if="menu1.menuLevel===2">目录</i>
                      <i v-if="menu1.menuLevel===3">按钮</i>
                    </el-col>
                    <el-col style="width: 700px">
                      <el-button v-has-permi="['/menu/saveMenu']" t type="success" icon="el-icon-edit" circle @click="showEditRoleForm(menu1)" />
                      <el-button v-has-permi="['/menu/delMenu/**']" type="danger" icon="el-icon-delete" circle @click="delRoleById(menu1.id)" />
                    </el-col>
                  </el-row>
                </template>
              </el-table-column>
              <el-table-column prop="name" width="140" align="center" />
              <el-table-column prop="url" width="230" align="center" />
              <el-table-column prop="path" width="200" align="center" />
              <el-table-column width="190" align="center">
                <template slot-scope="scope"><i>{{ scope.row.component }}.vue</i></template>
              </el-table-column>
              <el-table-column width="100" align="center">
                <template slot-scope="scope">
                  <i :class="scope.row.iconCls" /></template>
              </el-table-column>
              <el-table-column width="150" align="center">
                <template slot-scope="scope">
                  <i v-if="scope.row.menuLevel===1">菜单</i>
                  <i v-if="scope.row.menuLevel===2">目录</i>
                  <i v-if="scope.row.menuLevel===3">按钮</i>
                </template>
              </el-table-column>
              <el-table-column width="230" align="center">
                <template slot-scope="scope">
                  <el-button v-has-permi="['/menu/saveMenu']" type="success" icon="el-icon-edit" circle @click="showEditRoleForm(scope.row)" />
                  <el-button v-has-permi="['/menu/delMenu/**']" type="danger" icon="el-icon-delete" circle @click="delRoleById(scope.row.id)" />
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="权限名称" width="200" align="center" />
        <el-table-column prop="url" label="请求路径" width="200" align="center" />
        <el-table-column prop="path" label="组件路径" width="200" align="center" />
        <el-table-column label="组件名称" width="200" align="center">
          <template slot-scope="scope"><i>{{ scope.row.component }}.vue</i></template>
        </el-table-column>
        <el-table-column label="图标" width="100" align="center">
          <template slot-scope="scope">
            <i :class="scope.row.iconCls" /></template>
        </el-table-column>
        <el-table-column label="类别" width="200" align="center">
          <template slot-scope="scope">
            <i v-if="scope.row.menuLevel===1">菜单</i>
            <i v-if="scope.row.menuLevel===2">目录</i>
            <i v-if="scope.row.menuLevel===3">按钮</i>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" align="center">
          <template slot-scope="scope">
            <el-button v-has-permi="['/menu/saveMenu']" type="success" icon="el-icon-edit" circle @click="showEditRoleForm(scope.row)" />
            <el-button v-has-permi="['/menu/delMenu/**']" type="danger" icon="el-icon-delete" circle @click="delRoleById(scope.row.id)" />
          </template>
        </el-table-column>
      </el-table>
      <el-dialog :title="opr" :visible.sync="dialogFormVisible">
        <el-form ref="menuForm" :model="menuForm" :rules="menuFormRules" style="width: 650px">
          <el-form-item v-model="menuForm.parentId" label="上级菜单" :label-width="formLabelWidth" prop="parentId">
            <tree-select
              ref="treeRef"
              :data="treeMenuList"
              :default-props="defaultProps"
              node-key="id"
              :checked-keys="[menuForm.parentId]"
              @popoverHide="popoverHide"
            />
          </el-form-item>
          <el-form-item label="菜单等级" :label-width="formLabelWidth" prop="menuLevel" style="display: inline-block">
            <el-radio-group v-model="menuForm.menuLevel">
              <el-radio :label="1" disabled>一级</el-radio>
              <el-radio :label="2" disabled>二级</el-radio>
              <el-radio :label="3" disabled>三级</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="菜单状态" :label-width="formLabelWidth" prop="enabled" style="display: inline-block">
            <el-radio-group v-model="menuForm.enabled">
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="菜单图标" :label-width="formLabelWidth">
            <el-popover
              placement="bottom-start"
              width="460"
              trigger="click"
              @show="$refs['iconSelect'].reset()"
            >
              <IconSelect ref="iconSelect" @selected="selected" />
              <el-input slot="reference" v-model="menuForm.iconCls" placeholder="点击选择图标" style="width: 470px" readonly>
                <svg-icon
                  v-if=" menuForm.iconCls"
                  slot="prefix"
                  :icon-class=" menuForm.iconCls"
                  class="el-input__icon"
                  style="height: 32px;width: 16px;"
                />
                <i v-else slot="prefix" class="el-icon-search el-input__icon" />
              </el-input>
            </el-popover>
          </el-form-item>
          <el-form-item label="菜单名称" prop="name" :label-width="formLabelWidth" style="display: inline-block">
            <el-input v-model="menuForm.name" placeholder="请输入菜单名称" />
          </el-form-item>
          <el-form-item label="权限路径" prop="url" :label-width="formLabelWidth" style="display: inline-block">
            <el-input v-model="menuForm.url" placeholder="请输入权限路径" :readonly="menuForm.parentId===1" />
          </el-form-item>
          <el-form-item label="路由地址" prop="path" :label-width="formLabelWidth" style="display: inline-block">
            <el-input v-model="menuForm.path" placeholder="请输入路由地址" :readonly="menuForm.parentId===1" />
          </el-form-item>
          <el-form-item label="组件地址" prop="component" :label-width="formLabelWidth" style="display: inline-block">
            <el-input v-model="menuForm.component" placeholder="请输入组件地址" :readonly="menuForm.parentId===1" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeMenuForm">取 消</el-button>
          <el-button type="primary" @click="confirmMenuForm">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import { getAllMenuList, saveMenu, delMenu } from '@/api/menu'
import TreeSelect from '@/components/TreeSelect'
import IconSelect from '@/components/IconSelect'

export default {
// import引入的组件需要注入到对象中才能使用
  components: { TreeSelect, IconSelect },
  // props实现父子组件传递数据
  props: {},
  data() {
    return {
      defaultProps: {
        children: 'children', // 树形控件的子节点
        label: 'name' // 以权限名作为树形控件的显示值
      },
      formLabelWidth: '100px',
      dialogFormVisible: false,
      menuList: [],
      treeMenuList: [],
      queryStr: '',
      total: 0,
      opr: '新增菜单',
      menuForm: {
        id: undefined,
        url: '',
        path: null,
        component: null,
        name: '',
        iconCls: '',
        enabled: 1,
        menuLevel: 0,
        parentId: 0
      },
      menuFormRules: {
        // 为权限名称的所在的表单项定义验证规则
        name: [
          { required: true, message: '请输入菜单名称', trigger: 'blur' },
          { min: 3, max: 20, message: '菜单名称的长度在3~20个字符之间', trigger: 'blur' }
        ],
        parentId: [
          { required: true, message: '请选择上级菜单', trigger: 'blur' }
        ]
      }
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {
    menuForm: function(val) { // 语法：属性名:function(){} 即可实现对某个属性的数据进行监听
      this.$nextTick(function() {
        this.$refs.treeRef.$emit('updateCheckedKey')
      })
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {

  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getMenuList()
    this.getTreeMenuList()
  },
  // 方法集合
  methods: {
    selected(name) {
      this.menuForm.iconCls = name
    },
    popoverHide(checkedIds, checkedData) {
      this.menuForm.parentId = checkedData.id
      this.menuForm.menuLevel = parseInt(checkedData.menuLevel) + 1
      console.log('选中的菜单信息', checkedData)
      if (this.menuForm.menuLevel === 1) {
        this.menuForm.path = '/home'
        this.menuForm.component = '/Home'
        this.menuForm.url = '/'
      } else {
        this.menuForm.path = ''
        this.menuForm.component = ''
        this.menuForm.url = ''
      }
    },
    showEditRoleForm(menu) {
      console.log(menu)
      this.menuForm = menu
      if (menu.enabled === true) {
        this.menuForm.enabled = 1
      } else {
        this.menuForm.enabled = 0
      }
      console.log(menu)
      this.opr = '修改菜单'
      this.dialogFormVisible = true
    },
    delRoleById(id) {
      this.$confirm(
        '确定要删除当前菜单吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
        console.log(id)
        delMenu(id).then((res) => {
          if (res.code === 200) {
            console.log(res.code)
            this.getMenuList()
            this.$store.dispatch('menu/initRouters').then((data) => {
              // 将fmtRouters添加router路由中，即保存到router/index.js中
              this.$router.addRoutes(data) // 动态添加路由
            }).catch((err) => {
              console.log(err)
            })
          }
        })
      }).catch(() => {
        return this.$message.info('您取消了删除！')
      })
    },
    showAddMenuForm() {
      this.clearMenuForm()
      this.dialogFormVisible = true
    },
    clearMenuForm() {
      this.menuForm = {
        id: undefined,
        url: '/',
        path: '/home',
        component: '/Home',
        name: '',
        iconCls: '',
        enabled: 1,
        menuLevel: 1,
        parentId: 1
      }
      this.opr = '新增菜单'
    },
    closeMenuForm() {
      this.clearMenuForm()
      this.dialogFormVisible = false
    },
    confirmMenuForm() {
      console.log(this.menuForm)
      this.$refs['menuForm'].validate((valid) => {
        if (valid) {
          // 调用role.js中的saveRole方法发送请求到后端实现保存新增的角色信息
          saveMenu(this.menuForm).then((res) => {
            // false后隐藏添加操作员对话框
            this.dialogFormVisible = false
            if (res.code === 200) {
              // 新增成功后，再刷新角色列表数据
              this.getMenuList()
              // this.$store.dispatch('menu/initRouters').then((data) => {
              //   this.$router.addRoutes(data) // 1.动态添加路由
              //   global.antRouter = data // 2.将路由数据传递给全局变量，做侧边栏菜单渲染工作
              // })
              this.clearMenuForm()
              this.$store.dispatch('menu/initRouters').then((data) => {
                // 将fmtRouters添加router路由中，即保存到router/index.js中
                this.$router.addRoutes(data) // 动态添加路由
              }).catch((err) => {
                console.log(err)
              })
            }
          }).catch((err) => {
            console.log(err)
          })
        }
      })
    },
    getMenuList() {
      if (!this.menuList) {
        this.getMenus()
      } else {
        // eslint-disable-next-line no-redeclare,no-array-constructor
        var array = new Array()
        this.queryMenuList(this.queryStr, this.menuList, array)
        this.menuList = array
        console.log(this.menuList)
      }
    },
    getMenus() {
      // eslint-disable-next-line no-array-constructor
      getAllMenuList().then((res) => {
        this.menuList = res.data
      })
    },
    getTreeMenuList() {
      getAllMenuList().then((res) => {
        res.data.forEach(item1 => {
          if (item1.children && item1.children.length > 0) {
            item1.children.forEach(item2 => {
              item2.children = []
            })
          }
        })
        if (this.treeMenuList && this.treeMenuList.length > 0) {
          this.treeMenuList = []
        }
        this.treeMenuList.push({
          name: '主目录',
          id: 1,
          menuLevel: 0,
          children: res.data
        })
      })
    },
    queryMenuList(menuName, menuList, array) {
      if (menuName) {
        menuList.forEach((menu) => {
          if (!(menu.name.indexOf(menuName) === -1)) {
            array.push(menu)
          } else {
            if (menu.children != null && menu.children.length !== -1) {
              this.queryMenuList(menuName, menu.children, array)
            }
          }
        })
        array.forEach((menu) => {
          menu.menuLevel === 1
        })
      } else {
        this.getMenus()
      }
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 1) {
        return 'warning-row'
      } else if (rowIndex === 3) {
        return 'success-row'
      }
      return ''
    }
  } // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style>

  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
  .vcenter {
    display: flex;
    align-items: center;
    text-align: center;
    height: 50px;
  }

</style>
